package com.jinzo.mporaba;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
//import android.util.Log;

public class DBAdapter {
    public static final String KEY_ROWID = "_id";
    public static final String KEY_DISPLAYNAME = "displayName";
    public static final String KEY_PREPAID = "prepaid";   
    public static final String KEY_USED = "used"; 
    public static final String KEY_AVAILABLE = "available"; 
    public static final String KEY_UNIT = "unit"; 
    
//    private static final String TAG = "DBAdapter";
    private static final String DATABASE_NAME = "mobile_usage";
    private static final String DATABASE_TABLE = "usage";
    private static final int DATABASE_VERSION = 5;

    private static final String DATABASE_CREATE =
        "create table usage (_id integer primary key autoincrement, "
        + "displayName text not null," 
        + "prepaid integer not null,"
        + "unit text null," 
        + "available text null," 
        + "used text not null);";
        
    private final Context context; 
    
    protected DatabaseHelper DBHelper;
    protected SQLiteDatabase db;

    public DBAdapter(Context ctx) 
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }
        
    private static class DatabaseHelper extends SQLiteOpenHelper 
    {
        DatabaseHelper(Context context) 
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) 
        {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, 
        int newVersion) 
        {
            //Log.w(TAG, "Upgrading database from version " + oldVersion 
            //        + " to "
            //        + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS usage");
            onCreate(db);
        }
    }    
    
    public DBAdapter open() throws SQLException {
        db = DBHelper.getWritableDatabase();
        return this;
    }
    
    public void close() {
        DBHelper.close();
    }
    
    public long insertQuotaItem(QuotaItem q) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_DISPLAYNAME, q.getDisplayName());
        if (q.isPrepaid()) {
        	initialValues.put(KEY_PREPAID, 1);
        } else {
        	initialValues.put(KEY_PREPAID, 0);
        }
        initialValues.put(KEY_USED, q.getUsed());
        initialValues.put(KEY_UNIT, q.getUnit());
        initialValues.put(KEY_AVAILABLE, q.getAvailable());
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    public boolean insertOrUpdateQuotaItem(QuotaItem q) {
    		if (!this.updateQuotaItem(q)) {
    			this.insertQuotaItem(q);
    		}
    	return true;
    }
    
    public boolean deleteQuotaItem(long rowId) {
        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }
    
    public boolean deleteQuotaItem(String dp) {
        return db.delete(DATABASE_TABLE, KEY_DISPLAYNAME + "=" + dp, null) > 0;
    }
    
    public ArrayList<QuotaItem> getAllQuotaItems() {
        Cursor c = db.query(DATABASE_TABLE, new String[] {
        		KEY_ROWID, 
        		KEY_DISPLAYNAME,
        		KEY_PREPAID, 
        		KEY_UNIT,
        		KEY_AVAILABLE,
        		KEY_USED}, 
                null, 
                null, 
                null, 
                null, 
                null);
        ArrayList<QuotaItem> items = new ArrayList<QuotaItem>();
        if (c != null && (c.getCount() > 0)) {
        	c.moveToFirst();
        	do {
        		boolean prepaid = false;
        		if (c.getInt(2) == 1) {
        			prepaid = true;
        		} else {
        			prepaid = false;
        		}
        		items.add(new QuotaItem(c.getString(1), prepaid, c.getString(3), c.getString(4), c.getString(5)));
        	} while (!c.isLast() && c.moveToNext()); /* FIXIT: Hacky */
        	c.close();
        } 
        return items;
    }
    public QuotaItem getQuotaItem(String dp) throws SQLException {
        Cursor mCursor =
                db.query(true, DATABASE_TABLE, new String[] {
                		KEY_ROWID, 
                		KEY_DISPLAYNAME,
                		KEY_PREPAID, 
                		KEY_UNIT,
                		KEY_AVAILABLE,
                		KEY_USED }, 
                		KEY_DISPLAYNAME + "=" + dp, 
                		null,
                		null, 
                		null, 
                		null, 
                		null);
        if (mCursor != null) {
            mCursor.moveToFirst();
    		boolean prepaid = false;
    		if (mCursor.getInt(2) == 1) {
    			prepaid = true;
    		} else {
    			prepaid = false;
    		}
    		mCursor.close();
            return new QuotaItem(mCursor.getString(1), prepaid, mCursor.getString(3), mCursor.getString(4), mCursor.getString(5));
        }
        /* FIXIT: Classy, innit. */
        return new QuotaItem("ERROR", "ERROR");
    }


    public boolean updateQuotaItem(QuotaItem q) {
        ContentValues args = new ContentValues();
        if (q.isPrepaid()) {
        	args.put(KEY_PREPAID, 1);
        } else {
        	args.put(KEY_PREPAID, 0);
        }
        args.put(KEY_USED, q.getUsed());
        args.put(KEY_UNIT, q.getUnit());
        args.put(KEY_AVAILABLE, q.getAvailable());
        return db.update(DATABASE_TABLE, args, 
                         KEY_DISPLAYNAME + "= \"" + q.getDisplayName() +"\"", null) > 0;
    }
    
	public Cursor query(String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		qb.setTables("usage");
		Cursor c =qb.query(this.db, projection, selection, selectionArgs, null, null, sortOrder);
		return c;
	}
}
